#include "audiomanager.h"

AudioManager::AudioManager(QObject *parent) :
    QObject(parent)
{
    counter = 0;
    inputFile.setFileName(":/audio600.pcm");
    inputFile.open(QIODevice::ReadOnly);
    d600 = inputFile.readAll();
    inputFile.flush();
    inputFile.close();

    //   qDebug() << d600;

    /*  inputFile.setFileName("/home/user/audio1200_2.pcm");
    inputFile.open(QIODevice::ReadOnly);
    d1200 = inputFile.readAll();
    inputFile.close();
*/

    QAudioFormat format;
    format.setFrequency(44100);
    format.setChannels(1);
    format.setSampleSize(16);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);
    QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());


    //    foreach(const QAudioDeviceInfo &deviceInfo, QAudioDeviceInfo::availableDevices(QAudio::AudioOutput))
    //    qDebug() << "Device name: " << deviceInfo.deviceName() << deviceInfo.supportedByteOrders() << deviceInfo.supportedFrequencies() << deviceInfo.supportedCodecs() << deviceInfo.isFormatSupported(format);


    qDebug() << info.nearestFormat(format).byteOrder() << info.nearestFormat(format).channelCount() << info.nearestFormat(format).sampleRate();

    if (!info.isFormatSupported(format))
    {
        qWarning()<<"raw audio format not supported by backend, cannot play audio.";
        return;
    }
    audioOutput = new QAudioOutput(format, this);

    audioOutput->setBufferSize(17640*2);
    //  qDebug() << audioOutput->bufferSize();
    playbackDevice = audioOutput->start();


    playbackTimer = new QTimer(this);
    QObject::connect(playbackTimer,SIGNAL(timeout()),this,SLOT(startPlayback()));
    playbackTimer->start(500);



}

void AudioManager::startPlayback()
{
    //QtConcurrent::run(this,&AudioManager::play);
    play();
}

void AudioManager::stop()
{
    //TODO

}

void AudioManager::play()
{

    qDebug() << "play 1" <<  QDateTime::currentMSecsSinceEpoch() << d600.size();
    playbackDevice->write(d600.constData(),d600.size());
    qDebug() << "play 2" <<  QDateTime::currentMSecsSinceEpoch() << d600.size();
    emit onset();
}
